// stores/theme.ts
import { defineStore } from 'pinia'
import { ref, watchEffect } from 'vue'

type Theme = 'light' | 'dark'

export const useThemeStore = defineStore(
  'theme',
  () => {
    // 状态
    const theme = ref<Theme>('light')

    // 获取系统主题
    const getSystemTheme = (): Theme => {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
    }

    // 初始化主题
    const initTheme = () => {
      // 尝试从 localStorage 读取
      const savedTheme = localStorage.getItem('theme') as Theme | null
      const systemTheme = getSystemTheme()

      theme.value = savedTheme || systemTheme
      applyTheme(theme.value)
    }

    // 应用主题到 DOM
    const applyTheme = (newTheme: Theme) => {
      document.documentElement.setAttribute('data-theme', newTheme)
    }

    // 切换主题
    const toggleTheme = (newTheme?: Theme) => {
      if (newTheme) {
        theme.value = newTheme
      } else {
        theme.value = theme.value === 'light' ? 'dark' : 'light'
      }
      localStorage.setItem('theme', theme.value)
    }

    // 监听系统主题变化
    const watchSystemTheme = () => {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

      const handler = (e: MediaQueryListEvent) => {
        if (!localStorage.getItem('theme')) {
          theme.value = e.matches ? 'dark' : 'light'
        }
      }

      mediaQuery.addEventListener('change', handler)
      return () => mediaQuery.removeEventListener('change', handler)
    }

    // 初始化
    initTheme()
    const stopWatch = watchSystemTheme()

    // 自动应用主题变化
    watchEffect(() => {
      applyTheme(theme.value)
    })

    return {
      theme,
      toggleTheme,
    }
  },
  {
    persist: {
      key: 'theme-store',
      storage: localStorage,
      // paths: ['theme'],
    },
  },
)
